define('editorenhancer/insertarticle/InsertArticle', [
    'editorenhancer/insertarticle/insertarticle.css',
    'utils/fetchEnhancer',
    'utils/Time'], function(css, fetch, Time) {

const XEditor = window.XEditor;
const Dialog = XEditor.Dialog;

class InsertArticle extends XEditor.IWidget {
    constructor(button, editor) {
        super(editor);

        this.button = button;
        this.editor = editor;

        this.delayTimer = 0;
        this.dialogRef = null;
    }

    statusReflect() {}

    getHtml() {
        const html =
            ['<div class="xeditor-insertarticle-wrapper">',
                '<div class="insertarticle-form"><input type="text" placeholder="搜索文章" /></div>',
                '<div class="insertarticle-list"></div>',
            '</div>'].join('');

        return html;
    }

    getInput() {
        return this.dialogRef.getContentDom().querySelector('input[type="text"]');
    }
    getArticleWrapper() {
        return this.dialogRef.getContentDom().querySelector('.insertarticle-list');
    }

    renderList(res) {
        let _self = this;
        let list = res.data.data;
        let html = '';

        for(let i=0, len=list.length; i<len; i++) {
            html += '<a class="insertarticle-item" data-id="'+ list[i].id +'">'
                + list[i].title
                + ' - ' + Time.format('y-m-d', list[i].post_time * 1000)
                +'</a>';
        }

        this.getArticleWrapper().innerHTML = html;
    }

    doSearch(v) {
        fetch('/api/post/search', {
            method: 'POST',
            body: 'k=' + encodeURIComponent(v)
        }).then((res) => {
            if(0 === res.status) {
                this.renderList(res);
            } else {
                this.getArticleWrapper().innerHTML = '';
            }
        });
    }

    initEvent() {
        let _self = this;
        let input = this.getInput();
        let list = this.getArticleWrapper();

        input.oninput = (e) => {
            let v = e.target.value;
            if(!v) {
                return;
            }

            clearTimeout(_self.delayTimer);
            _self.delayTimer = setTimeout(() => {
                _self.doSearch(v);
            }, 500);
        };

        list.onclick = (e) => {
            let t = e.target;

            if('A' !== t.nodeName.toUpperCase()) {
                return;
            }

            let id = t.getAttribute('data-id');

            if(id) {
                XEditor.Editable.insertHtml(1, '<p>[x_insert_post id="'+ id +'"]</p>');
            }
            _self.dialogRef.close();
        };
    }

    onClick() {
        this.dialogRef = Dialog.getInstance().open(this.getHtml(), '插入文章', 0);

        this.initEvent();
    }
}

return InsertArticle;
});
